package cn.momoshenchi.service.impl;

import cn.momoshenchi.util.ParamsException;
import cn.momoshenchi.util.AssertUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.momoshenchi.pojo.Book;
import cn.momoshenchi.service.BookService;
import cn.momoshenchi.mapper.BookMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
 *
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>
implements BookService{

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public List<Book> search(String keyword)
    {

        return bookMapper.search(keyword);
    }

    @Override
    @Transactional(rollbackFor = ParamsException.class)
    public void insertWithEs(Book book) throws IOException
    {
        AssertUtil.isTrue(!this.save(book),"添加失败");
//        IndexRequest indexRequest = new IndexRequest("book");
//        indexRequest.id(book.getId().toString());
//        ObjectMapper objectMapper = new ObjectMapper();
//        String s = objectMapper.writeValueAsString(book);
//        indexRequest.source(s, XContentType.JSON);
//        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT.toBuilder().build());
    }

    @Override
    @Transactional(rollbackFor = ParamsException.class)
    public void insertListWithEs(List<Book> bookList) throws IOException
    {
        AssertUtil.isTrue(!this.saveBatch(bookList),"添加失败");
//        BulkRequest bulkRequest = new BulkRequest();
//        for (Book book : bookList)
//        {
//            IndexRequest indexRequest = new IndexRequest("book");
//            indexRequest.id(book.getId().toString());
//            ObjectMapper objectMapper = new ObjectMapper();
//            String s = objectMapper.writeValueAsString(book);
//            indexRequest.source(s, XContentType.JSON);
//            bulkRequest.add(indexRequest);
//        }
//        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT.toBuilder().build());
//        boolean failures = bulk.hasFailures();
    }
}




